#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "comm.hpp"

#define NAME "fifo"
#define PATH "."

class Fifo
{
public:
    Fifo(std::string path, std::string name)
        : _name(name), _path(path)
    {
        _fifoname = _path + "/" + _name;
        umask(0);
        // 新建管道
        _n = mkfifo(_fifoname.c_str(), 0666);
        if (_n < 0)
        {
            ERR_EXIT("mkfifo");
        }
        else
        {
            std::cout << "创建管道成功!" << std::endl;
        }
    }

    ~Fifo()
    {
        if (_n > 0)
            // 销毁管道
            unlink(_fifoname.c_str());
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _n;
};

class Openfifo
{
public:
    Openfifo(std::string path, std::string name)
        : _name(name), _path(path)
    {
        _filename = path + "/" + name;
    }

    ~Openfifo()
    {
    }

    void Open_for_write()
    {
        // 打开管道
        _fd = open(_filename.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open fifo");
        }
        else
        {
            std::cout << "打开管道成功" << std::endl;
        }
    }

    void open_for_read()
    {
        // 打开管道
        _fd = open(_filename.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open fifo");
        }
        else
        {
            std::cout << "打开管道成功" << std::endl;
        }
    }

    void wait()
    {
        char ch;
        int n=write(_fd, &ch, 1);
        if(n>0)printf("尝试唤醒\n");
    }

    bool wakeup()
    {
        char ch;
        int ret = read(_fd, &ch, 1);
        if (ret > 0)
        {
            printf("唤醒成功！\n");
            return true;
        }
        return false;
    }

    void Close()
    {
        close(_fd);
    }

private:
    std::string _path;
    std::string _name;
    std::string _filename;
    int _fd;
};
